import { defineStore } from "pinia";
import {
  getReturnDetail, //借调单查询详情
  submitReturnList, //归还提交
  getAddGoodsList, //借调单物资列表
} from "@/utils/api/InventoryManagement/IMreturn/IMreturn";
import { dictlist } from "@/utils/api/dict/dict"; //字典列表
import { useMemberStore } from "@/stores/modules/member";
import { useToastStore } from "@/stores/modules/toast";
//列表头
const addListHeader = [
  "物资名称",
  "单位",
  "批次",
  "有效期",
  "借调数量",
  "已还数量",
  "本次归还数量",
];

export const useIMreturnOtherStore = defineStore(
  "IMborrowOther",
  () => {
    const memberStore = useMemberStore();
    const toastStore = useToastStore();
    const LoanCode: any = ref(""); //借调单号
    const addOrdetailOrEdit = ref("add"); //、详情、编辑
    // 借调单物资表头
    const addtableHeader = addListHeader;
    // 借调类型列表
    let TypeList: any = [];
    let borrowTypeList: any = reactive({ TypeList });
    //获取类型列表
    const getGoodsTypeList = async () => {
      const res = await dictlist({
        DictStatus: "Normal",
        DictType: "BorrowType",
      });
      const arr = res.data.map((item: any) => {
        return {
          text: item.DictName,
          value: item.DictCode,
        };
      });
      borrowTypeList.TypeList = arr;
    };

    /******************************借调单***********************/
    //清空数据
    const clearData = () => {
      LoanCode.value = "";
      addOrdetailOrEdit.value = "add";
      addGoodsInfoList.addGoodsList = [];
      borrowOderDetail.borrowDetail = {};
    };
    // 物资信息列表
    const addGoodsList: any = [];
    const addGoodsInfoList: any = reactive({
      addGoodsList,
      currPage: 1,
      totalPage: 0,
    });

    //提交归还
    const submitReturnListOrder = async (data: any) => {
      if (isBorrowGoodsFull(formData)) {
        toastStore.show = true;
        toastStore.title = "请填写完整信息！";
        return;
      }
      if (isBorrowGoodsFull(addGoodsInfoList.addGoodsList)) {
        toastStore.show = true;
        toastStore.title = "请填写归还数量！";
        return;
      }
      const res: any = await submitReturnList({
        ReturnOperator: memberStore.user_id,
        LoanCode: LoanCode.value,
        ...formData,
        goods: handleSubmitBorrowData(addGoodsInfoList.addGoodsList) || [], //物资列表 obj
      });
      if (res.code == 0) {
        toastStore.show = true;
        toastStore.title = "归还成功！";
        toastStore.type = "success";
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 2000);
      }
    };
    //处理提交归还物资数据
    const handleSubmitBorrowData = (arr: any) => {
      let result: any = [];
      arr.forEach((obj: any) => {
        let formattedObj = {
          GoodsCode: obj["GoodsCode"] || null,
          GoodsBatch: obj["GoodsBatch"] || null,
          ExpirationDate: obj["ExpirationDate"] || null,
          BorrowBoxCode: obj["BorrowBoxCode"] || null,
          ReturnNo: obj["ReturnNo"] || 0,
        };
        result.push(formattedObj);
      });
      return result;
    };
    //判断物资是否填写完整
    const isBorrowGoodsFull = (item: any) => {
      let arr: any = item;
      let obj: any = item;
      let isNull: any = false;
      console.log("item", item);

      //判断是数组还是对象
      if (Array.isArray(item)) {
        if (arr.length == 0) {
          return false;
        }
        //判断是否有空值
        isNull = arr.some((item: any) => {
          return item.ReturnNo === "";
        });
      } else {
        //判断是否有空值
        isNull = Object.values(obj).some((item: any) => {
          return item === "" || item === null || item === undefined;
        });
      }

      return isNull;
    };
    // 获取物资信息列表
    const getAddGoods = async (data: any) => {
      const res: any = await getAddGoodsList({
        LoanCode: LoanCode.value,
        GodownCode: memberStore.GodownCode,
        searchParam: data.searchParam || "",
        pageNum: data.pageNum || 1,
        pageSize: data.pageSize || 10,
      });
      let arr: any = [];
      arr = res.data.list.map((item: any) => {
        item.ReturnNo = 0;
        return item;
      });
      //去重
      function compareObjects(obj1: any, obj2: any) {
        // 自定义比较两个对象是否相等的逻辑
        // 返回 true 表示相等，返回 false 表示不相等
        // 这里假设对象的属性都是简单类型，没有嵌套对象
        return obj1.Uuid === obj2.Uuid;
      }

      function removeDuplicateObjects(arr: any) {
        return arr.filter((el: any, index: any, self: any) => {
          return (
            index ===
            self.findIndex((obj: any) => {
              return compareObjects(obj, el);
            })
          );
        });
      }

      if (data.searchParam) {
        addGoodsInfoList.addGoodsList = res.data.list;
      } else {
        let oldaarr = JSON.parse(JSON.stringify(addGoodsInfoList.addGoodsList));
        let newarr = [...oldaarr, ...arr];
        addGoodsInfoList.addGoodsList = removeDuplicateObjects(newarr);
      }
      addGoodsInfoList.currPage = res.data.currPage;
      addGoodsInfoList.totalPage = res.data.totalPage;
      console.log("物资信息列表", addGoodsInfoList.addGoodsList);
    };
    /*******************************借调单详情************************/
    const formData: AnyObject = reactive({
      Returnee: "",
      ReturnDate: "",
      ReturnReason: "",
      ReturneeTel: "",
    });
    // 借调单详情
    const borrowOderDetail: any = reactive({});
    // 获取借调单详情
    const getReturnDetailData = async (data: any) => {
      const res: any = await getReturnDetail({
        LoanCode: data.LoanCode,
      });
      try {
        Object.assign(borrowOderDetail, res.data);
        const { Returnee, ReturnDate, ReturnReason, ReturneeTel } =
          borrowOderDetail;
        formData.Returnee = Returnee || "";
        formData.ReturnDate = ReturnDate || "";
        formData.ReturnReason = ReturnReason || "";
        formData.ReturneeTel = ReturneeTel || "";
      } catch (error) {
        console.log(error);
      }

      if (addOrdetailOrEdit.value == "edit") {
        formData.ReturnDate = getDate("");
      }
      console.log("借调单详情", borrowOderDetail);
    };
    //获取日期
    const getDate = (type: any) => {
      const date = new Date();
      let year: any = date.getFullYear();
      let month: any = date.getMonth() + 1;
      let day: any = date.getDate();
      //时分秒
      let hour: any = date.getHours();
      let minute: any = date.getMinutes();
      let second: any = date.getSeconds();
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      if (type === "start") {
        year = year - 60;
      } else if (type === "end") {
        year = year + 2;
      }
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    };
    return {
      addtableHeader,
      addGoodsInfoList,
      getAddGoods,
      LoanCode,
      addOrdetailOrEdit,
      submitReturnListOrder,
      getReturnDetailData,
      borrowOderDetail,
      clearData,
      borrowTypeList,
      getGoodsTypeList,
      formData,
    };
  },
  /**********************************TODO: 持久化***********************/
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
      paths: ["addtableHeader"],
    },
  }
);
